package com.bookkeeping.bookkeepingapi.web.api;


import com.alibaba.fastjson.JSON;
import com.bookkeeping.bookkeepingapi.model.User;
import com.bookkeeping.bookkeepingapi.repository.UserRepository;
import com.bookkeeping.bookkeepingapi.service.UserService;
import com.bookkeeping.bookkeepingapi.service.dto.ReturnDto;
import com.bookkeeping.bookkeepingapi.service.dto.UserDto;
import com.bookkeeping.bookkeepingapi.service.util.JwtUtil;
import com.bookkeeping.bookkeepingapi.service.util.MD5Util;
import com.bookkeeping.bookkeepingapi.web.vm.UserVM;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api") //下面所有接口前缀都有api
@AllArgsConstructor
@Slf4j
public class UserControler {
    private final UserRepository userRepository;
    private final UserService userSevice;

    //获取用户详细信息
    @GetMapping("/user")
    public String getDetail(HttpServletRequest request){

        //获取token
        String token =JwtUtil.getJwtFromRequest(request);
        //检查token是否传来
        if(StringUtils.isBlank(token))
        {
            return JSON.toJSONString((new ReturnDto(-1,"非法请求",null)));
        }
        //检查token是否传正确，是否是系统生成的令牌
        String userId="";
        try{
            userId=JwtUtil.parseToken(token);
        }catch (Exception e){
            //token过期
            return JSON.toJSONString(new ReturnDto(-9,"token过期" ,null));
        }
        Optional<User> user=userRepository.findById(Integer.parseInt(userId));
        if(!user.isPresent())
        {
            return JSON.toJSONString(new ReturnDto(-1,"系统不存在该用户",null));
        }
        return JSON.toJSONString(new ReturnDto(1,"查询成功",new UserDto(user.get())));
    }
    //查询列表接口
    @GetMapping("/users")
    public String getList(HttpServletRequest request){
        //获取token
        String token =JwtUtil.getJwtFromRequest(request);
        //检查token是否传来
        if(StringUtils.isBlank(token))
        {
            return JSON.toJSONString((new ReturnDto(-1,"非法请求",null)));
        }
        //检查token是否传正确，是否是系统生成的令牌
        //String userId=JwtUtil.parseToken(token);
        String userId="";
        try{
            userId=JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9,"token过期" ,null));
        }
        List<User> userList =userRepository.findAll();
        //是将user的list变成userDtoList
        List<UserDto> userDtos=userList.stream().map(x->new UserDto(x)).collect(Collectors.toList());
//        List<UserDto> userDtos1=userDtos.stream().filter(y->y.getRealname().startsWith("张")).collect(Collectors.toList());
//        System.out.println();
        //使用传统的for循环来写
//        List<UserDto> userDtos = new ArrayList<>();
//        for (User user : userList) {
//            UserDto userDto = new UserDto(user);
//            userDtos.add(userDto);
//        }
        return JSON.toJSONString(new ReturnDto(1,"查询成功",userDtos));
    }
    //注册用户，添加用户接口
    @PostMapping("/user")
    public String create(@RequestBody UserVM userVM) {
        //注册用户之前需要判断用户名是否以及在数据库中存在
        if (StringUtils.isBlank(userVM.getUsername())) {
            return JSON.toJSONString(new ReturnDto(-1, "用户名必传", null));
        }
        if (StringUtils.isBlank(userVM.getPassword()) || StringUtils.isBlank(userVM.getNewPassword())) {
            return JSON.toJSONString(new ReturnDto(-1, "密码必传", null));
        }
        if (StringUtils.isBlank(userVM.getRealname())) {
            return JSON.toJSONString(new ReturnDto(-1, "真实姓名必传", null));
        }
        if (!userVM.getPassword().equals(userVM.getNewPassword())) {
            return JSON.toJSONString(new ReturnDto(-1, "再次输入密码与密码不相等", null));
        }
        User user = userRepository.findFirstByUsername(userVM.getUsername());
        if(user!=null)
        {
            return JSON.toJSONString(new ReturnDto(-1,"该用户名已经被注册",null));
        }
        //添加或者注册用户
        user = userSevice.create(userVM);
        return JSON.toJSONString(new ReturnDto(1, "创建成功", new UserDto(user)));

    }

    //修改用户信息接口
   @PutMapping("/user/{id}")
    public String update(@PathVariable Integer id,@RequestBody UserVM userVM,HttpServletRequest request){
       //获取token
       String token =JwtUtil.getJwtFromRequest(request);
       //检查token是否传来
       if(StringUtils.isBlank(token))
       {
           return JSON.toJSONString((new ReturnDto(-1,"非法请求",null)));
       }
       //检查token是否传正确，是否是系统生成的令牌
       //String userId=JwtUtil.parseToken(token);
       String userId="";
       try{
           userId=JwtUtil.parseToken(token);
       }catch (Exception e){
           return JSON.toJSONString(new ReturnDto(-9,"token过期" ,null));
       }
       if(Integer.parseInt(userId)!=id){
           return JSON.toJSONString(new ReturnDto(-1,"非法编辑",null));
       }
        //先查询数据库中是否有该数据
        Optional<User> user = userRepository.findById(id);
        if(!user.isPresent()) {
            return JSON.toJSONString(new ReturnDto(-1, "系统中没有该用户信息", null));
        }
       if(StringUtils.isBlank(userVM.getRealname())){
           return JSON.toJSONString(new ReturnDto(-1, "真实姓名必传", null));
       }
       User updateUser=userSevice.update(user.get(),userVM);
       return JSON.toJSONString(new ReturnDto(1,"修改成功",new UserDto(updateUser)));
    }

    @DeleteMapping("/user/{id}")
    public String delete(@PathVariable Integer id, HttpServletRequest request){
        //获取token
        String token =JwtUtil.getJwtFromRequest(request);
        //检查token是否传来
        if(StringUtils.isBlank(token))
        {
            return JSON.toJSONString((new ReturnDto(-1,"非法请求",null)));
        }
        //检查token是否传正确，是否是系统生成的令牌
        //String userId=JwtUtil.parseToken(token);
        String userId="";
        try{
            userId=JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9,"token过期" ,null));
        }
        if(Integer.parseInt(userId)!=id){
            return JSON.toJSONString(new ReturnDto(-1,"非法删除",null));
        }
        //先查询数据库中是否有该数据
        Optional<User> user = userRepository.findById(id);
        if(!user.isPresent()) {
            return JSON.toJSONString(new ReturnDto(-1, "系统中没有该用户信息", null));
        }
        userSevice.delete(user.get());
        return JSON.toJSONString(new ReturnDto(1, "删除成功", null));
    }

    @PostMapping("/login")
    public String login(@RequestBody UserVM userVM){
        //先判断必传参数的校验
        if(StringUtils.isBlank(userVM.getUsername()) || StringUtils.isBlank(userVM.getPassword())){
            return JSON.toJSONString(new ReturnDto(-1, "用户名或密码必传", null));
        }
        //根据用户名查询数据的用户信息
        User user=userRepository.findFirstByUsername(userVM.getUsername());
        if(user==null){
            return JSON.toJSONString(new ReturnDto(-1,"系统中没有该用户",null));
        }
        if(!MD5Util.MD5(userVM.getPassword()).equals(user.getPassword()))
        {
            return JSON.toJSONString(new ReturnDto(-1,"密码错误，请重新输入",null));
        }
        //颁发JWT令牌
        String token = JwtUtil.generateToken(user.getId() + "");
        return JSON.toJSONString(new ReturnDto(1, "登录成功", token));
    }
}
